var express = require('express');
var router = express.Router();
var {loginModel,shopModel}=require('../model/models')
var jwt=require('jsonwebtoken')


//登录
router.post('/loginAdd',(req,res)=>{
  loginModel.create(req.body)
  res.send({
    code:200,
    msg:'添加用户成功'
  })
})
//登录
router.post('/login',async(req,res)=>{
  let {username,password}=req.body
  let data=await loginModel.findOne({username,password})
  if(data){
    let token="Bearar "+jwt.sign({username},'lce',{expiresIn:'1h'})
    res.send({
      code:200,
      msg:'登录成功',
      token
    })
  }else{
    res.send({
      code:201,
      msg:'登录失败'
    })
  }
})
//添加商品
router.post('/shopAdd',(req,res)=>{
  shopModel.create(req.body)
  res.send({
    code:200,
    msg:'添加商品成功',    
  })
})
//展示商品
router.get('/shoplist',async(req,res)=>{
const key=req.query.key
console.log(key,12);
let data;
if(key){
  const regex=new RegExp(key,"i")
  data=await shopModel.find({title:{$regex:regex}})
}else{
     data=await shopModel.find()
}

  res.send({
    code:200,
    msg:'展示成功',
    data
  })
})
//修改
router.post('/editshoplist/:id',async(req,res)=>{
  const id=req.params.id
  const {currentNum}=req.body
  let data=await shopModel.updateOne({_id:id},{$set:{currentNum:currentNum}})
  res.send({
    code:200,
    msg:'修改成功',
    data
  })
})

module.exports = router;
